package com.zhang.zhangapp.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;
import com.zhang.zhangapp.R;
import com.zhang.zhangapp.application.MApplication;
import com.zhang.zhangapp.base.config.BaseConfig;
import com.zhang.zhangapp.base.http.MCallback;
import com.zhang.zhangapp.bean.location.CityDao;
import com.zhang.zhangapp.bean.shop.Shop;
import com.zhang.zhangapp.bean.shop.ShopType;
import com.zhang.zhangapp.http.CommonHttp;
import com.zhang.zhangapp.utils.ScreenUtils;
import com.zhang.zhangapp.utils.T;
import com.zhang.zhangapp.view.adapter.ShopAdapter;
import com.zhang.zhangapp.view.custom.FilterPopupWindow;
import com.zhang.zhangapp.view.custom.HeadRefreshView;
import com.zhang.zhangapp.view.custom.ListViewInScrollView;
import com.zhang.zhangapp.view.shop.AllShopTypeActivity;
import com.zhang.zhangapp.view.shop.ShopDetailActivity;

import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 罗肖 on 2018/3/28.
 */

@ContentView(R.layout.fragment_nearby)
public class NearByFragment extends BaseLazyFragment {

    private final static int REQUEST_SEARCH = 10003;
    @ViewInject(R.id.nearby_listview)
    ListView hotListView;
    @ViewInject(R.id.action_bar_title)
    TextView titleText;

    ShopAdapter shopAdapter;

    private List<Shop> shopList = new ArrayList<>();

    @ViewInject(R.id.index_refresh_layout)
    PullToRefreshLayout refreshLayout;

    @ViewInject(R.id.nearby_nearby)
    TextView nearbyText;
    @ViewInject(R.id.nearby_all_type)
    TextView allTypeText;
    @ViewInject(R.id.nearby_order)
    TextView orderText;
    @ViewInject(R.id.nearby_filter)
    TextView filterText;
    @ViewInject(R.id.filters_layout)
    LinearLayout filterLayout;

    private double lon = 112.935181;
    private double lat = 28.218605;
    private String cityCode = "10001";

    Map<String, String> params = new HashMap<String, String>();

    List<Map<String, String>> nearbyMapList = new ArrayList<>();//附近数据
    List<Map<String, String>> orderMapList = new ArrayList<>();//排序数据
    Map<String, List<Map<String, String>>> objFilterMap = new HashMap<>(); //筛选数据对象
    List<Map<String, String>> filterMapList = new ArrayList<>();//筛选数据
    Map<String, List<Map<String, String>>> objAllTypeMap = new HashMap<>();

    FilterPopupWindow nearbyPopup;
    FilterPopupWindow orderPopup;
    FilterPopupWindow filterPopup;
    FilterPopupWindow allTypePopup;
    int[] popWindowLoc;//弹出菜单位置

    /**
     * 获取附近列表
     */
    MCallback getHotShopCallback = new MCallback() {
        @Override
        public void onSuccess(String data) {
            Gson gson = new Gson();
            List<Shop> list = gson.fromJson(data, new TypeToken<List<Shop>>() {
            }.getType());
            if (list != null) {
                shopList.addAll(list);
            }
            shopAdapter.notifyDataSetChanged();
            if (list.size() < BaseConfig.PAGE_SIZE) {
                refreshLayout.setCanLoadMore(false);
            }
        }

        @Override
        public void onSuccess(String message, String code) {
            refreshLayout.setCanLoadMore(false);
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            refreshLayout.setCanLoadMore(false);
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
            refreshLayout.setCanLoadMore(false);
        }

        @Override
        public void onFinished() {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            dismisionDalog();
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return x.view().inject(this, inflater, container);
    }

    @Override
    public void onFirstUserVisible() {
        initFilters();
        initParams();
        initHotListView();
        initRefreshLayout();
    }

    private void initParams() {
        params.put("lat", lat + "");
        params.put("lon", lon + "");
        params.put("range", "");//距离多少米（1000,3000,5000,10000,附近传1000）
        params.put("consumeRegion", "");//人均消费区间（0-50,50-100,100-300,300-500）
        params.put("orderkey", "");//排序规则(1 人气优先，2 离我最近，3 人均最高，4 人均最低，5 最新发布)
        params.put("cityCode", cityCode);
        params.put("keywords", "");
        params.put("pageSize", BaseConfig.PAGE_SIZE + "");
        params.put("typeCode", "");
    }

    private void initFilters() {

        nearbyMapList.clear();
        objFilterMap.clear();
        orderMapList.clear();
        objAllTypeMap.clear();
        nearbyPopup = null;
        orderPopup = null;
        filterPopup = null;
        allTypePopup = null;

        String[] nearbyArr = new String[]{"全部", "1KM", "3KM", "5KM", "10KM", "附近"};
        for (String str : nearbyArr) {
            Map<String, String> map = new HashMap<>();
            map.put("value", str);
            if ("全部".equals(str))
                map.put("value", "");
            if ("附近".equals(str))
                map.put("value", "1");

            map.put("label", str);
            map.put("selected", "false");
            nearbyMapList.add(map);
        }

        String[] filterArr = new String[]{"50以下", "50-100", "100-300", "300以上"};
        for (String str : filterArr) {
            Map<String, String> map = new HashMap<>();
            map.put("value", str);
            if ("50以下".equals(str))
                map.put("value", "0-50");
            if ("300以上".equals(str))
                map.put("value", "300-500");
            map.put("label", str);
            map.put("selected", "false");
            filterMapList.add(map);
        }
        objFilterMap.put("价格", filterMapList);

        String[] orderArr = new String[]{"人气优先", "离我最近", "人均最高", "人均最低", "最新发布"};
        for (int i = 0; i < orderArr.length; i++) {
            Map<String, String> map = new HashMap<>();
            map.put("value", (i + 1) + "");
            map.put("label", orderArr[i]);
            map.put("selected", "false");
            orderMapList.add(map);
        }

        List<ShopType> shopTypeList = MApplication.getInstance().getShopTypeArrayList();
        if (shopTypeList != null) {
            for (ShopType type : shopTypeList) {
                List<Map<String, String>> list = new ArrayList<>();
                Map<String, String> mapAll = new HashMap<>();
                mapAll.put("value", type.getCode());
                mapAll.put("label", "全部");
                mapAll.put("selected", "false");
                list.add(mapAll);
                for (ShopType childType : type.getChild()) {
                    Map<String, String> map = new HashMap<>();
                    map.put("value", childType.getCode());
                    map.put("label", childType.getName());
                    map.put("selected", "false");
                    list.add(map);
                }
                objAllTypeMap.put(type.getName(), list);
            }
            // 全部大类
            List<Map<String, String>> listAll = new ArrayList<>();
            Map<String, String> mapAll1 = new HashMap<>();
            mapAll1.put("value", "");
            mapAll1.put("label", "全部");
            mapAll1.put("selected", "false");
            listAll.add(mapAll1);
            objAllTypeMap.put("全部", listAll);
        }
    }

    private void initHotListView() {
        shopAdapter = new ShopAdapter(shopList, getContext());
        hotListView.setAdapter(shopAdapter);
        hotListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(NearByFragment.this.getActivity(), ShopDetailActivity.class);
                intent.putExtra("shopCode", shopList.get(i).getShopCode());
                NearByFragment.this.getActivity().startActivity(intent);
            }
        });
        getHotShops(1);
    }

    /**
     * @param view
     */
    @Event(type = View.OnClickListener.class, value = {R.id.action_bar_title})
    private void shopTypeCilck(View view) {
        switch (view.getId()) {
            case R.id.action_bar_title: {//搜索
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                intent.putExtra("goShopList", false);
                startActivityForResult(intent, REQUEST_SEARCH);
            }
            break;
        }
    }

    @Event(type = View.OnClickListener.class, value = {R.id.nearby_all_type, R.id.nearby_filter, R.id.nearby_nearby, R.id.nearby_order})
    private void onFilterClick(View view) {
        switch (view.getId()) {
            case R.id.nearby_all_type: {
                if (popWindowLoc == null)
                    popWindowLoc = ScreenUtils.calculatePopWindowPos(filterLayout);
                if (allTypePopup == null) {
                    allTypePopup = new FilterPopupWindow(getContext(), objAllTypeMap, popWindowLoc[1]);
                    allTypePopup.setonItemClick(new FilterPopupWindow.onItemClick() {
                        @Override
                        public void onItemClick(Map<String, String> map) {
                            params.put("typeCode", map.get("value"));
                            allTypePopup.dismiss();
                            allTypeText.setSelected(false);
                            getHotShops(1);
                        }
                    });
                    allTypePopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            allTypeText.setSelected(false);
                        }
                    });
                }
                allTypePopup.showAtLocation(filterLayout, Gravity.NO_GRAVITY, popWindowLoc[0], popWindowLoc[1]);
                allTypeText.setSelected(true);
            }
            break;
            case R.id.nearby_filter: {
                if (popWindowLoc == null)
                    popWindowLoc = ScreenUtils.calculatePopWindowPos(filterLayout);
                if (filterPopup == null) {
                    filterPopup = new FilterPopupWindow(getContext(), objFilterMap, popWindowLoc[1]);
                    filterPopup.setonItemClick(new FilterPopupWindow.onItemClick() {
                        @Override
                        public void onItemClick(Map<String, String> map) {
                            params.put("consume", map.get("value"));
                            filterPopup.dismiss();
                            filterText.setSelected(false);
                            getHotShops(1);
                        }
                    });
                    filterPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            filterText.setSelected(false);
                        }
                    });
                }
                filterPopup.showAtLocation(filterLayout, Gravity.NO_GRAVITY, popWindowLoc[0], popWindowLoc[1]);
                filterText.setSelected(true);
            }
            break;
            case R.id.nearby_nearby:
                if (popWindowLoc == null)
                    popWindowLoc = ScreenUtils.calculatePopWindowPos(filterLayout);
                if (nearbyPopup == null) {
                    nearbyPopup = new FilterPopupWindow(getContext(), nearbyMapList, popWindowLoc[1]);
                    nearbyPopup.setonItemClick(new FilterPopupWindow.onItemClick() {
                        @Override
                        public void onItemClick(Map<String, String> map) {
                            params.put("range", map.get("value"));
                            nearbyPopup.dismiss();
                            nearbyText.setSelected(false);
                            getHotShops(1);
                        }
                    });
                    nearbyPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            nearbyText.setSelected(false);
                        }
                    });
                }
                nearbyPopup.showAtLocation(filterLayout, Gravity.NO_GRAVITY, popWindowLoc[0], popWindowLoc[1]);
                nearbyText.setSelected(true);
                break;
            case R.id.nearby_order:
                if (popWindowLoc == null)
                    popWindowLoc = ScreenUtils.calculatePopWindowPos(filterLayout);
                if (orderPopup == null) {
                    orderPopup = new FilterPopupWindow(getContext(), orderMapList, popWindowLoc[1]);
                    orderPopup.setonItemClick(new FilterPopupWindow.onItemClick() {
                        @Override
                        public void onItemClick(Map<String, String> map) {
                            params.put("orderkey", map.get("value"));
                            orderPopup.dismiss();
                            orderText.setSelected(false);
                            getHotShops(1);
                        }
                    });
                    orderPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            orderText.setSelected(false);
                        }
                    });
                }
                orderPopup.showAtLocation(filterLayout, Gravity.NO_GRAVITY, popWindowLoc[0], popWindowLoc[1]);
                orderText.setSelected(true);
                break;
        }
    }

    /**
     * 初始化headerView
     */
    private void initRefreshLayout() {
        refreshLayout.setHeaderView(new HeadRefreshView(getContext()));
        refreshLayout.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                initParams();
                initFilters();
                getHotShops(1);
            }

            @Override
            public void loadMore() {
                getHotShops(shopList.size() / BaseConfig.PAGE_SIZE + 1);
            }
        });
    }

    /**
     * 获取热门推荐
     *
     * @param pageNo
     */
    private void getHotShops(int pageNo) {
        if (pageNo == 1) {
            shopList.clear();
            shopAdapter.notifyDataSetChanged();
            refreshLayout.setCanLoadMore(true);
        }
        if (MApplication.getInstance().getMapLocation() != null) {
            lat = MApplication.getInstance().getMapLocation().getLatitude();
            lon = MApplication.getInstance().getMapLocation().getLongitude();
            cityCode = CityDao.queryCityCode(MApplication.getInstance().getMapLocation().getCity().replace("市", ""));
            params.put("lat", lat + "");
            params.put("lon", lon + "");
        }
        if (showLoadingDialog()) {
            params.put("pageNum", pageNo + "");
            CommonHttp.commonHttp("hzg/shop/queryShop", params, getHotShopCallback);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case REQUEST_SEARCH:
                    String keyword = data.getStringExtra("keyword");
                    params.put("keywords", keyword);
                    getHotShops(1);
                    titleText.setText(keyword);
                    break;
            }
        }
    }
}
